package FrequentSequenceMining;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Timer;

import util.FileHandler;

public class Main {
	private static final int NUMSEQUENCESPRINTED = Integer.MAX_VALUE;
	private static final String INPUTFILE = "alladin";
	private static final String BESTSEQUENCESFILENAME = "bestsequences" + INPUTFILE + SequenceList.MINFREQUENCY +".txt";
	private static final int MINLENGTH = 3;
	private static final String NUMBERRESULTSFILENAME = "number" + BESTSEQUENCESFILENAME;
	
	public static void main(String[] args) {
		FileHandler fh = FileHandler.getInstance();
		fh.deleteFile(NUMBERRESULTSFILENAME);
		
		long startTime = Calendar.getInstance().getTimeInMillis();
		Data d = Data.getInstance();
		d.readFile(INPUTFILE+".txt");
		System.out.println("Input file read");
		long readTime = Calendar.getInstance().getTimeInMillis();
		
		fh.write("Time to read file: " + (readTime - startTime)+"\n", NUMBERRESULTSFILENAME);
		ArrayList<Sequence> lengthOneSequences = d.getLengthOneSequences();
		SequenceList sl = SequenceList.getInstance();
		sl.setLengthOneSequences(lengthOneSequences);
		boolean newSequencesPossible = true;
		System.out.println("Generating sequences with frequency >= " + SequenceList.MINFREQUENCY);
		int n = 1;
		
		long beforeGeneration = Calendar.getInstance().getTimeInMillis();
		long generating = beforeGeneration;
		while(newSequencesPossible) {
			fh.write("Sequences of length " + n + " " + sl.getAllSequences().get(n-1).size()+"\n", NUMBERRESULTSFILENAME);
			System.out.println("Generating sequences of length " + ++n);
			newSequencesPossible = sl.generateNewSequences();
			long currentTime = Calendar.getInstance().getTimeInMillis();
			fh.write("Time to generate length "+ (n+1) +": " + (currentTime - generating)+"\n", NUMBERRESULTSFILENAME);
			generating = currentTime;
		}
		fh.write("Total generation time: "+ (Calendar.getInstance().getTimeInMillis() - beforeGeneration)+"\n", NUMBERRESULTSFILENAME);
		fh.write("Total time: "+ (Calendar.getInstance().getTimeInMillis() - startTime)+"\n", NUMBERRESULTSFILENAME);
		System.out.println("Sequences generated, saving into file");
		printResults();
	}

	@SuppressWarnings("unchecked")
	private static void printResults() {
		ArrayList<ArrayList<Sequence>> sequences = SequenceList.getInstance().getAllSequences();
		ArrayList<Sequence> globalList = new ArrayList<Sequence>();
		for(int i = MINLENGTH-1; i < sequences.size(); ++i) {
			globalList.addAll(sequences.get(i));
		}
		Collections.sort(globalList);
		Collections.reverse(globalList);
		util.FileHandler fh = util.FileHandler.getInstance();
		fh.deleteFile(BESTSEQUENCESFILENAME);
		for(int i = 0; i < NUMSEQUENCESPRINTED && i < globalList.size(); ++i) {
			fh.write(globalList.get(i)+ " " +globalList.get(i).getFrequency() +  "\n", BESTSEQUENCESFILENAME);
		}
		System.out.println("Finished!");
	}

}
